package com.lwq.fast.log.trace.filter;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lwq.fast.log.fastlogcore.constant.Constants;
import com.lwq.fast.log.fastlogcore.trace.TraceThreadLocal;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author 刘文强
 *
 * 日志链路过滤器
 */
public class LogTraceFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try{
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            //先从header中取traceId,如果取不到，在生成
            String traceId = request.getHeader(Constants.TRACE_ID);
            if (StrUtil.isBlank(traceId)){
                traceId = IdUtil.simpleUUID();
            }
            TraceThreadLocal.set(traceId);
            filterChain.doFilter(servletRequest, servletResponse);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            TraceThreadLocal.remove();
        }

    }

    @Override
    public void destroy() {
        TraceThreadLocal.remove();
    }
}
